﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Text;
using System.Collections.Generic;
public class StoryPlayer : MonoBehaviour
{
    [SerializeField] Image m_BlackMask;
    [SerializeField] Image m_CgImageUI;
    [SerializeField] Text m_StoryTextUI;
    [SerializeField] Text m_BacklogTextUI;
    [SerializeField] GameObject m_InputTip;
    [SerializeField] GameObject m_BacklogTextObj;
    [SerializeField] GameObject m_StoryTextObj;
    [SerializeField] TextAsset m_StoryScript;
    [SerializeField, Tooltip("播放完这段剧情后下一个要读取的场景")] int m_NextSceneId;
    /// <summary>
    /// 保存片段种类，p(icture)表示切换Cg，t(ext)表示显示文本
    /// </summary>
    Queue<string> clipTypes;
    /// <summary>
    /// 保存信息，如果clipMessages在clipTypes对应位置为p则表示Cg图片的名字，t则显示故事文本
    /// </summary>
    Queue<string> clipMessages;
    /// <summary>
    /// 保存已读文本
    /// </summary>
    StringBuilder backlogText; 
    StringBuilder clipTextBuilder;
    bool canRecieveInput = false;
    AudioSource audioSource;
    private void Awake()
    {
        audioSource = GetComponent<AudioSource>();
        string[] clips = m_StoryScript.text.Split('|');
        string[] clipdetails;
        clipTypes = new Queue<string>(clips.Length);
        clipMessages = new Queue<string>(clips.Length);
        for (int i = 0; i < clips.Length; i++)
        {
            clipdetails = clips[i].Split('#');
            clipTypes.Enqueue(clipdetails[0]);
            clipMessages.Enqueue(clipdetails[1]);
        }
        backlogText = new StringBuilder(10000);
        clipTextBuilder = new StringBuilder(150);
    }
    private void Start()
    {
        StartCoroutine(HideBlackMaskAndPlayFirstClip());       
    }
    private void Update()
    {
        if (canRecieveInput && !m_BacklogTextObj.activeInHierarchy)
        {
            if (Input.GetButtonDown(Constants.Text_Input_ShowNext) || Input.GetMouseButtonDown(0))
                GetClip();
        }
        if (Input.GetButtonDown(Constants.Text_Input_ShowHideBacklog))
            ShowOrHideBacklogText();
    }
    void GetClip()
    {
        if (clipMessages.Count == 0)
        {
            canRecieveInput = false;
            m_InputTip.SetActive(canRecieveInput);
            StartCoroutine(ShowBlackMaskAndLoadScenes());
            return;
        }
        string type = clipTypes.Dequeue();
        string message = clipMessages.Dequeue();
        if (type.Contains("p")) //用Contains是因为有可能有换行符
            StartCoroutine(ChangePicture(message));
 
        else if (type.Contains("t"))
            StartCoroutine(ChangeText(message));
        else
            StartCoroutine(ChangeBgm(message));
    }
    IEnumerator ChangeBgm(string bgmName)
    {
        float t = 1f;
        canRecieveInput = false;
        m_InputTip.SetActive(canRecieveInput);
        while (t > 0.02f)
        {
            t -= Time.deltaTime;
            audioSource.volume = t;
            yield return new WaitForEndOfFrame();
        }
        audioSource.volume = 1f;
        if (bgmName != "null")
        {
            audioSource.clip = GlobalData.MusicDictionary[bgmName].Music;
            audioSource.Play();
            GlobalData.MusicDictionary[bgmName].CanbeListened = true;
        }
        else
            audioSource.Stop();
        GetClip();
    }
    IEnumerator ChangePicture(string pictureName)
    {
        float t = 0f;
        canRecieveInput = false;
        m_InputTip.SetActive(canRecieveInput);
        Material renderMaterial = m_CgImageUI.materialForRendering;
        renderMaterial.SetTexture("_MainTex", renderMaterial.GetTexture("_SecondTex"));
        if (pictureName != "null")
        {
            renderMaterial.SetTexture("_SecondTex", GlobalData.CgDictionary[pictureName].Cg);
            GlobalData.CgDictionary[pictureName].CanbeSeem = true;
        }
        else
            renderMaterial.SetTexture("_SecondTex", Texture2D.blackTexture);
        while (t < 1f)
        {
            t += Time.deltaTime;
            renderMaterial.SetFloat("_LerpWeight", t);
            yield return new WaitForEndOfFrame();
        }
        renderMaterial.SetFloat("_LerpWeight", 1f);
        GetClip();
    }
    IEnumerator ChangeText(string storytextclip)
    {
        clipTextBuilder.Remove(0, clipTextBuilder.Length);
        int idx = 0;
        canRecieveInput = false;
        m_InputTip.SetActive(canRecieveInput);
        while (idx < storytextclip.Length)
        {
            clipTextBuilder.Append(storytextclip[idx]);
            m_StoryTextUI.text = clipTextBuilder.ToString();
            yield return new WaitForSeconds(Time.fixedDeltaTime); //一秒最多显示50个字符
            idx++;
        }
        canRecieveInput = true;
        backlogText.Append(storytextclip.Replace(" ","")).AppendLine().AppendLine();
        m_BacklogTextUI.text = backlogText.ToString();
        m_InputTip.SetActive(canRecieveInput);
    }
    IEnumerator ShowBlackMaskAndLoadScenes()
    {
        float t = 1f;
        canRecieveInput = false;
        m_InputTip.SetActive(canRecieveInput);
        while (t > 0.02f)
        {
            t -= Time.deltaTime;
            audioSource.volume = t;
            yield return new WaitForEndOfFrame();
        }
        t = 0f;
        Color c = Color.black;
        c.a = 0f;
        while (t < Constants.ShowBlackMaskTime)
        {
            t += Time.deltaTime;
            c.a = Mathf.Lerp(0f, 1f, t / Constants.ShowBlackMaskTime);
            m_BlackMask.color = c;
            yield return new WaitForEndOfFrame();
        }
        c.a = 1f;
        m_BlackMask.color = c;
        Material renderMaterial = m_CgImageUI.materialForRendering;
        renderMaterial.SetTexture("_MainTex", null);   //用的是共享材质，所以要初始化
        renderMaterial.SetTexture("_SecondTex", null);
        GlobalData.SaveNextScene = m_NextSceneId;
        GlobalData.Save();
        SceneManager.LoadScene(m_NextSceneId);
    }
    IEnumerator HideBlackMaskAndPlayFirstClip()
    {
        float t = 0f;
        Color c = Color.black;
        c.a = 1f;
        while (t < Constants.ShowBlackMaskTime)
        {
            t += Time.deltaTime;
            c.a = Mathf.Lerp(1f, 0f, t / Constants.ShowBlackMaskTime);
            m_BlackMask.color = c;
            yield return new WaitForEndOfFrame();
        }
        c.a = 0f;
        m_BlackMask.color = c;
        GetClip();
    }

    public void ShowOrHideBacklogText()
    {
        //交换两个对象的active状态
        bool backlogState = m_StoryTextObj.activeInHierarchy;
        m_StoryTextObj.SetActive(m_BacklogTextObj.activeInHierarchy);
        m_BacklogTextObj.SetActive(backlogState);
        canRecieveInput = !backlogState; //如果backlogState为true则不能输入
    }
}
